#!/bin/bash
# resner@e.email, resner@notabug.org

help="
mnt/unmounter.sh	unmount a device previously mounted with mnt/mounter.sh.

	[args]

	-h			show help.
*	-d (/dev/xyz)		specify device.
"

error() {
	printf "\e[31mError\e[0m: %s\n" "$1"
}

print() {
	printf "%s\n" "$1"
}

while getopts hd: option; do
	case $option in
		h)	print "$help"
			exit;;
		d) device="$OPTARG";;
		\?) error "Unknown flag passed."
			exit 1
			;;
	esac
done

if [ ! $UID == 0 ]; then
	error "Please run as root."
	exit 1
fi

if [[ -z "$device" || ! -b "$device" ]]; then
	error "Drive not specified, doesn't exist, or it is not a block device."
	exit 1
fi

UUID=$(lsblk -n -o UUID $device)
print "Selected disk UUID: $UUID"
if [ -z "$UUID" ]; then
	error "Could not get UUID of $device."
	exit 1
fi

mount_dir="/mnt/$UUID"
print "Mount directory: $mount_dir"

if [ ! -d "$mount_dir" ]; then
	error "Supposed mount directory doesn't exist ($mount_dir)."
	exit 1
fi

read -p "Is this reasonable? (y/n) " &&
[ $REPLY == "y" ] || exit 1

print "Unmounting $device."
umount $device
print "Deleting $mount_dir."
rm -rf "$mount_dir"